package logic

import (
	"errors"
	"github.com/gogap/logs"
	"github.com/shopspring/decimal"
	"strconv"
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/models/devices"
	"yundian/internel/app/models/orders"
	"yundian/internel/app/models/refunds"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/wechatpay"
)

// ------------------------ 退款订单逻辑处理 ---------------------------------- //

func (logic *OrderLogic) HandleRefundLogic(resultData *wechatpay.PayData) error {
	orderInfo := dao.NewOrderDao().GetOrderInfoByOutTradeNo(resultData.Get("transaction_id")).Unwrap().(*orders.OrderModel) // 订单信息
	dao.NewRefundDao().DeleteRefundNull(orderInfo.TradeNo).Unwrap()  // 删除空退款
	dao.NewOrderDao().DeleteDividendsLog(orderInfo.TradeNo).Unwrap() // 删除分红

	// 新增退款
	err := logic.HandleRefundInsertRefund(resultData, orderInfo.Appid, orderInfo.Mchid)
	if err != nil {
		logs.Info("新增退款异常 ==========>", orderInfo.TradeNo)
		return err
	}
	// 订单结算金额
	refundsTotal := dao.NewOrderDao().GetRefundsByTransactionIdTotal(resultData.Get("transaction_id")).Unwrap().(int64)
	newSettlementMoney := decimal.NewFromInt(orderInfo.SettlementMoney).Sub(decimal.NewFromInt(refundsTotal)).IntPart()

	// 更新订单信息
	if newSettlementMoney <= 0 {
		dao.NewOrderDao().UpdateOrderState(orderInfo.Id, 3).Unwrap() // 更新订单状态
	} else {
		dao.NewOrderDao().UpdateOrderSettlementMoney(orderInfo.Id, newSettlementMoney).Unwrap() // 修改订单结算金额
		devInfo := dao.NewOrderDao().GetDeviceInfo(orderInfo.DeviceSn).Unwrap().(*devices.DeviceType)
		dingo.Task(NewOrderLogic().CalOrderDividends, func() {}, orderInfo, devInfo, newSettlementMoney, int64(orderInfo.EndAt)) // 重新分红
	}
	return nil
}

// 订单提现退款专用
func (logic *OrderLogic) HandleRefLogic(resultData *wechatpay.PayData) error {
	orderInfo := dao.NewOrderDao().GetOrderInfoByOutTradeNo(resultData.Get("transaction_id")).Unwrap().(*orders.OrderModel) // 订单信息
	// 新增退款
	err := logic.HandleRefundInsertRefund(resultData, orderInfo.Appid, orderInfo.Mchid)
	if err != nil {
		logs.Info("新增退款异常 ==========>", orderInfo.TradeNo)
		return err
	}
	return nil
}

// 新增退款信息
func (logic *OrderLogic) HandleRefundInsertRefund(resultData *wechatpay.PayData, appid, mchid string) error {

	amountMap := wechatpay.NewPayData()
	_ = amountMap.FromJsonStr(resultData.Get("amount"))                       // 退款信息
	refundMoney, _ := strconv.ParseInt(amountMap.Get("refund"), 10, 64)       // 退款金额
	payerRefund, _ := strconv.ParseInt(amountMap.Get("payer_refund"), 10, 64) // 支付退款金额
	payerTotal, _ := strconv.ParseInt(amountMap.Get("payer_total"), 10, 64)   // 订单支付金额
	totalFee, _ := strconv.ParseInt(amountMap.Get("total"), 10, 64)           // 订单总金额

	m := refunds.New()
	m.RefundNo = resultData.Get("out_refund_no")    // 商户退款单号
	m.OutRefundNo = resultData.Get("refund_id")     // 微信退款号
	m.TradeNo = resultData.Get("out_trade_no")      // 商户订单号
	m.OutTradeNo = resultData.Get("transaction_id") // 微信支付单号
	m.RefundFee = refundMoney                       // 退款金额
	m.SettlementRefundFee = payerRefund             // 支付退款金额
	m.SettlementTotalFee = payerTotal               // 订单支付金额
	m.TotalFee = totalFee                           // 订单总金额

	m.RefundAccount = resultData.Get("refund_account")
	m.RefundRecvAccout = resultData.Get("refund_recv_accout")
	m.RefundRequestSource = resultData.Get("user_received_account") // 退款帐号
	m.RefundStatus = resultData.Get("refund_status")  // 退款状态

	layout := "2006-01-02T15:04:05+08:00"
	//successTime, _ := time.Parse(layout, resultData.Get("success_time"))  utc
	successTime, _ := time.ParseInLocation(layout, resultData.Get("success_time"), time.Local)
	m.SuccessTime = dingo.Time(successTime.Unix())

	m.Appid = appid
	m.Mchid = mchid
	m.CreateAt = dingo.Time(time.Now().Unix())
	m.UpdateAt = dingo.Time(time.Now().Unix())

	c := dao.NewRefundDao().CountRefundByOutRefundNo(m.OutRefundNo).Unwrap().(int64)
	if c > 0 {
		logs.Info("======== 退款记录已存在 =========")
		return errors.New("退款记录已经存在")
	}
	db := dao.NewRefundDao().InsertRefund(m)
	if db.Err != nil {
		return db.Err
	}
	logs.Info("======== 退款记录新增成功 =========")
	return nil
}




